package com.weizhu.swufer.core.cluster;

import com.weizhu.swufer.constant.SwuferConstant;
import com.weizhu.swufer.core.client.Invoker;
import com.weizhu.swufer.core.client.ReferenceConfig;
import com.weizhu.swufer.core.server.SwuferBootstrap;
import com.weizhu.swufer.core.util.BeanUtil;

import java.util.Properties;

public interface Cluster {

    Class<?> DEFAULT_CLUSTER = FailoverCluster.class;

    AbstractClusterInvoker createClusterInvoker();

    static Invoker getClusterInvoker(ReferenceConfig config){
        Class<?> clusterClass = config.getClusterClass();
        if (clusterClass == null){
            Properties properties = SwuferBootstrap.getInstance().getProperties();
            String clusterProperty = properties.getProperty(SwuferConstant.PROPERTIES_CLUSTER);
            if (clusterProperty != null && !clusterProperty.contains(".")){
                clusterProperty = "com.weizhu.swufer.core.cluster." + clusterProperty;
            }
            if (clusterProperty != null){
                try {
                    clusterClass = Class.forName(clusterProperty);
                }catch (ClassNotFoundException e){
                    throw new IllegalStateException("cluster class " + clusterProperty + " not exist");
                }
            }else {
                clusterClass = Cluster.DEFAULT_CLUSTER;
            }
            if (!Cluster.class.isAssignableFrom(clusterClass)){
                throw new IllegalStateException("class " + clusterClass.getName() + " has not implements Cluster.class");
            }
        }
        Cluster cluster = (Cluster)BeanUtil.createInstance(clusterClass);
        AbstractClusterInvoker clusterInvoker = cluster.createClusterInvoker();
        clusterInvoker.setLoadBalancerClass(config.getLoadBalancerClass());
        return clusterInvoker;
    }
}
